﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.Business;
using YiSha.Entity.OrganizationManage;
using YiSha.Model.Param.Business;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;

namespace YiSha.Service.OrganizationManage
{
    public class EyeFollowUpService : RepositoryFactory
    {
        private DepartmentService departmentService = new DepartmentService();

        private PersonService personService = new PersonService();

        private PrescriptionService prescriptionService = new PrescriptionService();

        #region 获取数据
        public async Task<List<EyeFollowUpEntity>> GetList(EyeFollowUpParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<EyeFollowUpEntity>> GetPageList(EyeFollowUpParam param, Pagination pagination)
        {
            //var expression = ListFilter(param);
            //var list = await this.BaseRepository().FindList(expression, pagination);

            StringBuilder strSql = new StringBuilder();
            var parameter = new List<DbParameter>();

            strSql.Append(@"select a.*,b.RealName,b.Gender,b.Birthday,b.Mobile,b.DepartmentId,c.DepartmentName from BsEyeFollowUp a 
                        left join BsPerson b on a.PersonId = b.Id
                        left join SysDepartment c on b.DepartmentId = c.Id where 1=1 and a.baseIsdelete=0 ");

            strSql.Append(" and  a.PrescriptionId=@PrescriptionId");
            parameter.Add(DbParameterExtension.CreateDbParameter("@PrescriptionId", param.PrescriptionId));

            if (param != null)
            {
                if (!string.IsNullOrEmpty(param.Key))
                {
                    strSql.Append(" and (b.RealName like @key or b.RealNameEn like @key or b.Mobile like @key )");

                    parameter.Add(DbParameterExtension.CreateDbParameter("@key", "%" + param.Key + "%"));
                }



            }

            var list = await this.BaseRepository().FindList<EyeFollowUpEntity>(strSql.ToString(), parameter.ToArray(), pagination);

            return list.ToList();
        }

        public async Task<EyeFollowUpEntity> GetEntity(long id)
        {

            var model = this.BaseRepository().FindEntity<EyeFollowUpEntity>(id).Result;


            var prescriptionModel = prescriptionService.GetEntity(model.PrescriptionId).Result;

            var personModel = personService.GetEntity(prescriptionModel.PersonId.Value).Result;


            model.RealName = personModel.RealName;
            model.Gender = personModel.Gender;
            model.Birthday = personModel.Birthday;
            model.CreateTime = personModel.BaseCreateTime.Value.ToString("yyyy-MM-dd");


            return model;
        }

        public bool ExistName(EyeFollowUpEntity entity)
        {
            var expression = LinqExtensions.True<EyeFollowUpEntity>();
            expression = expression.And(t => t.BaseIsDelete == 0);
            if (entity.Id.IsNullOrZero())
            {
                expression = expression.And(t => t.PersonId == entity.PersonId && t.ThisDate == entity.ThisDate && t.BaseIsDelete == 0);
            }
            else
            {
                expression = expression.And(t => t.PersonId == entity.PersonId && t.BaseIsDelete == 0 && t.ThisDate == entity.ThisDate && t.Id != entity.Id);
            }
            return this.BaseRepository().IQueryable(expression).Count() > 0 ? true : false;
        }
        #endregion

        #region 提交数据
        public async Task SaveForm(EyeFollowUpEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                await entity.Create();
                await this.BaseRepository().Insert<EyeFollowUpEntity>(entity);
            }
            else
            {
                await entity.Modify();
                await this.BaseRepository().Update(entity);
            }
        }

        public async Task<int> GetMaxSort(long id)
        {
            object result = await this.BaseRepository().FindObject("SELECT MAX(FollowUpSort) FROM BsEyeFollowUp where PrescriptionId=" + id + "");
            int sort = result.ParseToInt();
            sort++;
            return sort;
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<EyeFollowUpEntity>(idArr);
        }
        #endregion

        #region 私有方法
        private Expression<Func<EyeFollowUpEntity, bool>> ListFilter(EyeFollowUpParam param)
        {
            var expression = LinqExtensions.True<EyeFollowUpEntity>();
            if (param != null)
            {
                if (!string.IsNullOrEmpty(param.Key))
                {
                    // expression = expression.And(t => t.RealName.Contains(param.Key) || t.ContactsName.Contains(param.Key) || t.Mobile.Contains(param.Key) || t.RealNameEn.Contains(param.Key));
                }




                if (!string.IsNullOrEmpty(param.DepartmentId))
                {
                    var dps = Convert.ToInt64(param.DepartmentId.Split(",").Last());
                    var departmentEntity = departmentService.GetList(dps);


                    //expression = expression.And(t => departmentEntity.Result.Select(e => e.Id).ToList().Contains(t.DepartmentId) || t.DepartmentId == dps);
                }

            }



            return expression;
        }
        #endregion
    }
}
